package com.pcbly.web.persistence.publicinfo;

/**
 * @author carl.song
 * Copyright (c) 2010 Lightsoft, International.
 * All rights reserved.
 *
 */
import java.util.List;

import com.pcbly.web.components.utils.random.GUID;
import com.pcbly.web.bean.publicinfo.MobileSetBean;
import com.pcbly.web.persistence.HibernateBaseDao;
import com.pcbly.web.components.hibernate.support.Page;

@SuppressWarnings("unchecked")
public class MobileSetHibernateDao extends HibernateBaseDao<MobileSetBean>
		implements MobileSetDao {
	/**
	 * 
	 */
	private static final long serialVersionUID = -747316508753484287L;

	protected Class<MobileSetBean> getEntityClass() {
		return MobileSetBean.class;
	}

	public MobileSetHibernateDao() {
		super();
	}

	@Override
	public MobileSetBean saveMobileSetBean(MobileSetBean publicinfo)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug(publicinfo.getId());
		}
		String id = (new GUID()).toString();
		publicinfo.setId(id);
		getHibernateTemplate().save(publicinfo);
		return publicinfo;
	}

	@Override
	public void removeMobileSetBeanByIds(String ids) throws Exception {
		// TODO Auto-generated method stub
		ids = ids.replaceAll(",", "','");
		String hsql = "update t_publicinfo_mobileset set RECYCLED='1' where ID in( '"
				+ ids + "')";
		getSession().createSQLQuery(hsql).executeUpdate();

	}

	@Override
	public void removeMobileSetBeanById(String id) throws Exception {
		// TODO Auto-generated method stub
		id = id.replaceAll(",", "','");
		String hsql = "update t_publicinfo_mobileset set RECYCLED='1' where ID= '"
				+ id + "'";
		getSession().createSQLQuery(hsql).executeUpdate();

	}

	public Page<MobileSetBean> findMobileSetBeanByCond(MobileSetBean bean,
			Page<MobileSetBean> page, String orderByName, boolean asc)
			throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("select * from t_publicinfo_mobileset where RECYCLED='0' ");
		if (!(bean == null)) {
		}
		if (asc) {
			// criteria.addOrder(Order.asc(orderByName));
			sb.append(" order by  ");
			sb.append(orderByName);
			sb.append(" ");
		} else {
			// criteria.addOrder(Order.desc(orderByName));
			sb.append(" order by  ");
			sb.append(orderByName);
			sb.append(" desc ");
		}
		Object obj = getSession().createSQLQuery(
				"select count(*)  " + removeSelect(removeOrders(sb.toString()))
						+ " ").uniqueResult();
		if (obj == null) {
			obj = "0";
		}

		page.setTotalCount(Integer.parseInt(String.valueOf(obj)));
		if (page.getTotalCount() > 0) {
			int first = page.getFirst();
			int lpage = first + page.getPageSize();
			if (lpage > page.getTotalCount()) {
				lpage = page.getTotalCount();
			}
			List<MobileSetBean> beans = getSession().createSQLQuery(
					sb.toString()).addEntity(MobileSetBean.class).list()
					.subList(first, lpage);
			page.setResult(beans);
		}
		return page;
	}
}